import {defineStore} from "pinia"
import {getUser, login, register, updateUser} from "@/service/api"
import {commons} from "@/utils/commons";

// 定义state类型 (也可以不定义)
interface AuthState {
    userInfo: {} | null
    token: string | null
}

export const useAuthStore = defineStore("auth", {
    state: (): AuthState => ({
        userInfo: uni.getStorageSync('userInfo') || null,
        token: null,
    }),
    actions: {
        // 用户注册
        async userRegister(params: object) {
            await register(params).then(res => {
                this.userInfo = res.data
                this.token = res.data.token
                console.log(res.data)
                commons.showToast('登录成功~')
                this.setStorage(res.data)
            })
        },

        // 用户登录
        async userLogin(params: object) {
            await login(params).then(res => {
                this.userInfo = res.data
                this.token = res.data.token
                this.setStorage(res.data)
            })
        },

        // 获取用户信息
        async getUserInfo() {
            await getUser().then(res => {
                this.userInfo = res.data
                this.setStorage(res.data)
            })
        },

        // 用户更新
        async userUpdate(params: object) {
            await updateUser(params).then(res => {

            })
        },

        setStorage(data: any) {
            uni.setStorageSync('userInfo', data)
            uni.setStorageSync('token', data.token)
        }
    }
})
